package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lutzyt.delivery.bean.Commodity;
import com.lutzyt.delivery.bean.OrderItem;
import com.lutzyt.delivery.mapper.OrderItemDAO;
import com.lutzyt.delivery.service.CommodityService;
import com.lutzyt.delivery.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDAO, OrderItem> implements OrderItemService {

  private OrderItemDAO orderItemDAO;
  private CommodityService commodityService;

  @Transactional(readOnly = true)
  @Override
  public OrderItem findById(Integer id) {
    return orderItemDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public Page<OrderItem> findByPage(int pageNum, int pageSize, int orderId) {
    QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("order_id", orderId);
    return this.page(new Page<>(pageNum, pageSize), queryWrapper);
  }

  @Override
  public void insert(OrderItem orderItem) {
    orderItemDAO.insert(orderItem);
  }

  @Override
  public void update(OrderItem orderItem) {
    orderItemDAO.updateById(orderItem);
  }

  @Override
  public void deleteById(Integer id) {
    orderItemDAO.deleteById(id);
  }

  @Override
  public List<OrderItem> findByOrderId(Integer id) {
    final List<OrderItem> list = this.lambdaQuery().eq(OrderItem::getOrderId, id).list();
    list.forEach(this::setCommodity);
    return list;
  }

  @Override
  public Page<OrderItem> pageByOrderId(Integer id, Integer pageSize, Integer pageNum) {
    QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("order_id", 0);
    final Page<OrderItem> page = this.page(new Page<>(pageNum, pageSize), queryWrapper);
    page.getRecords().forEach(this::setCommodity);
    return page;
  }

  private void setCommodity(OrderItem item){
    if (item.getCommodityId() != null){
      Commodity commodity = commodityService.findById(item.getCommodityId());
      item.setCommodity(commodity);
    }
  }

  @Autowired
  public void setOrderItemDAO(OrderItemDAO orderItemDAO) {
    this.orderItemDAO = orderItemDAO;
  }

  @Autowired
  public void setCommodityService(CommodityService commodityService) {
    this.commodityService = commodityService;
  }
}